package com.enhe.gck.com;

import cn.hutool.core.collection.CollectionUtil;
import com.enhe.gck.CarbonBaseConstant;
import com.enhe.gck.com.oracle.LwdHttpConfig;
import com.enhe.gck.communal.PublicMethod;
import com.enhe.gck.item.BatchHWANE20386Item;
import com.enhe.gck.pojo.Batch;
import com.enhe.gck.service.impl.BatchService;
import com.kuangkie.carbon.common.IntegrationMsg;
import com.kuangkie.carbon.panel.CarbonPanel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class TimingMethod {

    @Resource
    private BatchService batchService;


    @Scheduled(cron = "*/1 * * * * ?")
    public void reportCurrentTime() {
        CarbonPanel.changeCurrentProgram(Long.valueOf(LwdHttpConfig.programCode));
        List<Batch> batchList = PublicMethod.query(CarbonBaseConstant.出场批次_ccpc)
                .addLessOrEqual(BatchHWANE20386Item.基本属性组_过期时间, new Date())
                .addEqual(BatchHWANE20386Item.基本属性组_启用, true)
                .goBack().queryBeans(Batch.class);
        if (batchList != null && !batchList.isEmpty()) {
            for (Batch batch : batchList) {
                String id = String.valueOf(batch.getId());
                String logPrefix = "【ID：" + id + "】";
                log.info("{}修改批号为不启用 num：{}", logPrefix, batch.getNumber());
                List<Batch> toUpdateList = new ArrayList<>();

                batch.setIsUsing(false);
                toUpdateList.add(batch);    // 当前批次

                LocalDate now = LocalDate.now();
                if (Objects.nonNull(batch.getSumResidue()) && batch.getSumResidue().compareTo(BigDecimal.valueOf(0)) > 0) {
                    // 不启用该编号时存在剩余量，启用同类型编号（如果存在；新批次数量>=剩余量）
                    List<Batch> availableBatchList = batchService.getAvailableBatchListWithoutPackageDate(batch.getType(), batch.getBatchType());
                    if (CollectionUtil.isNotEmpty(availableBatchList)) {
                        BigDecimal targetResidue = batch.getSumResidue();
                        BigDecimal nResidue = BigDecimal.ZERO;
                        for (int i = 0; i < availableBatchList.size(); i++) {
                            Batch nb = availableBatchList.get(i);
                            nResidue = nResidue.add(nb.getSumResidue());
                            nb.setPackageDate(now);
                            nb.setFailureTime(now.plusDays(3));
                            toUpdateList.add(nb);   // 新批次修改后加入待修改列表
                            log.info("{}启用同类型新批号：id：{}，num：{}", logPrefix, nb.getId(), nb.getNumber());

                            if ((i == availableBatchList.size() - 1) && targetResidue.compareTo(nResidue) > 0) {
                                log.info("{}可启用的批次的剩余量不足！", logPrefix);
                                break;
                            }
                            if (targetResidue.compareTo(nResidue) <= 0) {
                                break;
                            }
                        }
                    }else {
                        log.info("{}该类型的批号没有可用的新批号，id：{}，num：{}  过磅时可能会出现过磅失败问题！", logPrefix, id, batch.getNumber());
                    }
                }

                Collection<IntegrationMsg> msgColl = CarbonPanel.getRecordIntegration(CarbonBaseConstant.出场批次_ccpc).integrate(toUpdateList);
                if (msgColl.stream().anyMatch(msg -> !msg.success())) {
                    String errMsg = msgColl.stream().filter(msg -> !msg.success()).map(IntegrationMsg::getRefuseMsgContentStr).collect(Collectors.joining());
                    log.error("{}修改批号启用状态/包装日期、失效日期失败!原因:{}", logPrefix, errMsg);
                }else {
                    log.info("{}修改批号启用状态/包装日期、失效日期成功!【{}】", logPrefix, toUpdateList.stream().map(Batch::getNumber).collect(Collectors.joining(",")));
                }
            }
        }
    }
}